package com.ibm.cognos.imt.service;

import com.ibm.cognos.imt.config.BiServerConfig;
import groovy.lang.GroovyClassLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: eric
 * Date: 2/10/14
 * Time: 5:07 PM
 * To change this template use File | Settings | File Templates.
 */
@Service
public class GroovyScriptHelper {
    @Autowired
    BiServerConfig biServerConfig;

    private String imports() {
        return "import ibm.cognos.imt.*\n" +
                "import ibm.cognos.imt.chart.*\n"+
                "import ibm.cognos.imt.template.*\n"+
                "import ibm.cognos.imt.dataUsage.*\n" ;
    }

    private String beginning() {
        return "class MyReport extends CogReport {\n" +
//                "\n" +
//                "    def revenue = dataItem(\"[Sales (query)].[Sales].[Revenue]\")\n" +
//                "    def year = dataItem(\"[Sales (query)].[Time].[Year]\")\n" +
//                "    def productLine = dataItem(\"[Sales (query)].[Products].[Product line]\")\n" +
//                "    def country = dataItem(\"[Sales (query)].[Branch].[Country]\")" +
                "\n";
    }

    private String ending() {
        return " }\n";
    }

    public String getSpecDefinition(String code) {
        String generated = imports() + beginning() + code + ending();
        System.out.println(generated);
        return generated;
    }

//    public static Object invokeMethod(GroovyObject obj, String methodName, Object[] args) throws IOException, IllegalAccessException, InstantiationException {
////        ClassLoader parent = GroovyScriptHelper.class.getClassLoader();
////        GroovyClassLoader loader = new GroovyClassLoader(parent);
////        Class groovyClass = loader.parseClass(new File("app/models/groovy/CogReport.groovy"));
////
////// let's call some method on an instance
////        GroovyObject groovyObject = (GroovyObject) groovyClass.getDeclaredConstructor(String.class).newInstance();
//
//        Object result = (Object) obj.invokeMethod(methodName, args);
//        return result;
//    }


    public String invokeGenerateSpecMethod(String code) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
//        ClassLoader parent = getClass().getClassLoader();
//        GroovyClassLoader loader = new GroovyClassLoader(parent);
//        InputStream groovyClassIS = GroovyCompiler.class
//                .getResourceAsStream("/org/jboss/loom/tools/groovy/Foo.groovy");

//        InputStream is = new ByteArrayInputStream( getSpecDefinition(code).getBytes() );

        GroovyClassLoader gcl = new GroovyClassLoader();
//        List<String> paths = getClasspath();
//        for (String path : paths) {
//            gcl.addClasspath(path);
//        }
        Class clazz = gcl.parseClass(getSpecDefinition(code));
        if (clazz != null) {

            Object obj = clazz.newInstance();
            Method generateSpecMethod = clazz.getMethod("getSpec");
            Method methods[] = clazz.getSuperclass().getDeclaredMethods();
            for (Method method : methods) {
                if (method.getName().equals("modelPath")) {
                    System.out.println(method.getName());
                    method.invoke(obj, new Object[]{biServerConfig.getModelPath()});
//                    method.invoke(obj, new Object[]{"/content/folder[@name='Samples']/folder[@name='Models']/package[@name='GO Sales (query)']/model[@name='model']"});
                }
            }
//        Method modelPahtMethod = clazz.getSuperclass().getMethod("modelPath", new Class[]{String.class});


//                clazz.getMethod("modelPath", new Class[]{String.class});
//        modelPahtMethod.invoke(obj, new Object[]{"/content/folder[@name='Samples']/folder[@name='Models']/package[@name='GO Sales (query)']/model[@name='model']"});
            return (String) generateSpecMethod.invoke(obj, new Object[]{});
        } else {
            throw new InstantiationError();
        }

    }

    private List<String> getClasspath() {
        List<String> paths = new ArrayList<String>();
//        URL url = (Thread.currentThread().getContextClassLoader()).getResource("/");
//        String path = url.getPath();
//        String rootPath = path.replace("app", "bin/production/CognosReport");
//        System.out.println(path);
//        paths.add(url.getPath());
        paths.add("C:\\workspace\\CognosReport\\bin\\production\\CognosReport");
        return paths;
    }


}
